package com.gamerole.app.page.source

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.gamerole.app.entity.ArticleBean
import com.gamerole.app.service.HttpService
import javax.inject.Inject
private const val STARTING_PAGE_INDEX = 1
private const val NETWORK_PAGE_SIZE = 10
class ArticlePagingSource constructor(private var httpService: HttpService,private var type:Int) :
    PagingSource<Int, ArticleBean>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleBean> {
        val pageNumber = params.key ?: STARTING_PAGE_INDEX
        val pageSize = params.loadSize

        // 加载数据
        val data = httpService.getWxArticle(page = pageNumber, pagesize = pageSize, season_type = type)

        return try {

            data.data.let {
                val nextKey = if (it!!.list!!.isEmpty()) {
                    null
                } else {
                    // initial load size = 3 * NETWORK_PAGE_SIZE
                    // ensure we're not requesting duplicating items, at the 2nd request
                    // 初次加载 params.loadSize 为 NETWORK_PAGE_SIZE 3倍数量
                    // position = 1 params.loadSize = 90 NETWORK_PAGE_SIZE = 30
                    // 后续 paging 加载 params.loadSize 为 NETWORK_PAGE_SIZE 数量
                    // position = 5 params.loadSize = 30 NETWORK_PAGE_SIZE = 30
                    // position = 4 params.loadSize = 30 NETWORK_PAGE_SIZE = 30
                    pageNumber + (params.loadSize / NETWORK_PAGE_SIZE)
                }
                LoadResult.Page(
                    data = it!!.list!!,
                    prevKey = if (pageNumber == STARTING_PAGE_INDEX) null else pageNumber - 1,
                    nextKey = nextKey
                )
            }
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    fun setType(type:Int):ArticlePagingSource{
        this.type=type
        return this
    }
    override fun getRefreshKey(state: PagingState<Int, ArticleBean>): Int? {
        return null
    }
}